package com.jeedcp.gen.rest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import javax.servlet.http.HttpServletResponse;

import com.jeedcp.gen.config.MsConfigProperties;
import com.jeedcp.gen.model.Components;
import com.jeedcp.gen.model.DbInfo;
import com.jeedcp.gen.model.ProjectInfo;
import com.jeedcp.gen.utils.DBUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import com.jeedcp.gen.enums.ComponentsEnum;
import com.jeedcp.gen.utils.ProcessUtil;

import cn.org.rapid_framework.generator.util.FileHelper;

@RestController
@RequestMapping("/gen")
public class GenMSRest {
    Logger logger = LoggerFactory.getLogger(GenMSRest.class);
    @Autowired
    MsConfigProperties msConfigProperties;


    @RequestMapping(value = "/ms", method = RequestMethod.GET)
    public String ms(
            @RequestParam(required = true) String projectName,
            @RequestParam(required = true) String group,
            @RequestParam(required = true) String copyright,
            @RequestParam(required = true) String author,
            @RequestParam(required = true) String dbUrl,
            @RequestParam(required = true) String dbPort,
            @RequestParam(required = true) String dbName,
            @RequestParam(required = true) String dbUsername,
            @RequestParam(required = true) String dbPassword,
            @RequestParam(required = true, defaultValue = "") String c) throws Exception {
        //基本信息
        Map<String, Object> root = new HashMap<String, Object>();
        String packageName = group.replaceAll("\\.", "\\/");
        root.put("project", new ProjectInfo(projectName, group, copyright, author, packageName));
        root.put("dbInfo", new DbInfo(dbUrl, dbPort, dbName, dbUsername, dbPassword));
        String url = "jdbc:mysql://" + dbUrl + ":" + dbPort + "/information_schema?serverTimezone=Hongkong&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true";
        //校验连接是否成功
        Connection connection = DBUtil.getCon(url, dbUsername, dbPassword);
        if (connection.isClosed()) {
            return "无法连接数据库,请检查数据库配置信息,是否自动创建数据";
        } else {
            //创建数据库
            String url2 = "jdbc:mysql://" + dbUrl + ":" + dbPort + "/"+dbName+"?serverTimezone=Hongkong&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true";
            //校验连接是否成功

            try{
                Connection connection2 = DBUtil.getCon(url2, dbUsername, dbPassword);
                if (connection2.isClosed()) {
                    Statement stat = connection2.createStatement();
                    stat.executeUpdate("create database " + dbName);
                }
            }catch (Exception ex){
                    Statement stat = connection.createStatement();
                    stat.executeUpdate("create database " + dbName);
            }


        }
        //组件
        root.put("components", new Components(c.split(",")));
        String templateDir = msConfigProperties.getTemplateDir();
        logger.info("templateDir:" + templateDir);
        String outDir = msConfigProperties.getOutDir();
        logger.info("outDir:" + outDir);
        //do
        execute(root, templateDir, outDir);

        return "生成初始工程成功!!!";
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(HttpServletResponse response) throws IOException {
        String list = ComponentsEnum.values().toString();
        return list;
    }

    private void execute(Map<String, Object> root, String templateDir, String outDir) {
        File templateBaseDir = null;
        try {
            templateBaseDir = ResourceUtils.getFile("classpath:template");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取所有的目录及文件的相对目录
        List<File> srcFiles = FileHelper.searchAllNotIgnoreFile(templateBaseDir);
        for (int i = 0; i < srcFiles.size(); i++) {
            File srcFile = srcFiles.get(i);
            //获取每一个file的相对路径
            String filePath = FileHelper.getRelativePath(templateBaseDir, srcFile);
            if (filePath.length() == 0 || filePath.indexOf("$") == -1) {
                continue;
            }
            //获取路径上所有的变量,并替替换成定义的值
            String filePathVariables[] = filePath.split(Matcher.quoteReplacement("$"));
            for (String filePathVariable : filePathVariables) {
                if (filePathVariable.indexOf("{") == -1) {
                    continue;
                }
                String columnName = filePathVariable.substring(filePathVariable.indexOf("{") + 1, filePathVariable.indexOf("}"));
                String[] columnNames = columnName.split("\\.");

                String value = null;
                //根据key获取value,ps:key可能是多级 begin
                Map<String, Object> focusMap = root;
                for (String focusColumnName : columnNames) {
                    Object get = focusMap.get(focusColumnName);
                    if (get instanceof String) {
                        value = get == null ? null : get.toString();
                        break;
                    } else if (get instanceof Map) {
                        focusMap = ((Map) get);
                    }
                }
                //根据key获取value,ps:key可能是多级 end
                //替换文件名,并去除无用字符
                filePath = filePath.replace(columnName, value);
                filePath = filePath.replace("{", "").replaceAll("}", "").replace("$", "");
            }

            //创建文件夹
            logger.info(filePath);
            //是文件夹先创建,不是则渲染模板
            File tmp = new File(outDir + filePath);
            out:
            if (!tmp.exists()) {
                if (tmp.getName().indexOf(".") > -1) {
                    //属于文件
                    break out;
                }
                tmp.mkdirs();
            }
            if (tmp.isDirectory()) {
                continue;
            }
            //渲染
            if (filePath.endsWith(".iml")||filePath.endsWith(".jar")||filePath.endsWith(".vue")||filePath.endsWith(".png")
                    ||filePath.endsWith(".jpg")||filePath.endsWith(".gif")) {
                try {
                    FileUtils.copyFile(srcFile,tmp);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else if (filePath.contains("-ui")) {
                if (filePath.contains("config\\index.js")) {
                    ProcessUtil.process(tmp, new File(srcFile.getPath().replace(tmp.getName(), "")), root);
                } else {
                    try {
                        FileUtils.copyFile(srcFile,tmp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                ProcessUtil.process(tmp, new File(srcFile.getPath().replace(tmp.getName(), "")), root);
            }

        }
    }

//    @RequestMapping(value = "/lnglat", method = RequestMethod.GET)
//    public List<Map<String, Object>> lnglat() {
//        List<Map<String, Object>> result = null;
//        try {
//            result = DBUti2.query("SELECT lng,lat FROM `t_area_in_out_lastest` where enter_date>=CURRENT_DATE");
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//        return result;
//
//    }
}
